package com.ruoyi.project.erp.service.impl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.project.erp.domain.*;
import com.ruoyi.project.erp.dto.CompleteTaskDto;
import com.ruoyi.project.erp.dto.CreateTaskDTO;
import com.ruoyi.project.erp.dto.UpdateTaskDTO;
import com.ruoyi.project.erp.mapper.*;
import com.ruoyi.project.erp.vo.*;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysRoleMapper;
import com.ruoyi.project.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.ruoyi.project.erp.service.ITaskService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 任务Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-06-19
 */
@Service
public class TaskServiceImpl implements ITaskService 
{
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private TaskMemberMapper taskMemberMapper;
    @Autowired
    private ProjectUserMapper projectUserMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private WorklogMapper worklogMapper;
    private static final BigDecimal TOTAL_HOURS_IN_DAY = new BigDecimal("24");
    /**
     * 查询任务
     * 
     * @param id 任务主键
     * @return 任务
     */
    @Override
    public Task selectTaskById(Long id)
    {
        return taskMapper.selectTaskById(id);
    }
    @Override
    public TaskDetialVO selectTaskDetailById(Long id)
    {
        return taskMapper.selectTaskDetailById(id);
    }

    @Override
    public List<TaskListVO> getMyTaskByProject(String projectId) {
        // 1. 参数校验
        if (!StringUtils.hasText(projectId)) {
            return Collections.emptyList();
        }

        // 2. 获取当前登录用户的钉钉ID (dd_user_id)
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        String ddUserId = currentUser.getDdUserId(); // <-- 这是关键改动

        // 健壮性判断
        if (!StringUtils.hasText(ddUserId)) {
            return Collections.emptyList();
        }

        // 3. 调用Mapper层方法，传入钉钉ID和项目ID
        return taskMapper.selectMyTasksByProjectId(ddUserId, projectId);
    }

    @Override
    public int batchAddTaskToAllProjects(Task taskTemplate) {
        String operator = SecurityUtils.getUsername();
        String taskName = taskTemplate.getTaskName();
// --- 核心修改在这里 ---
        Date now = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.YEAR, 10); // 在当前日期上加10年
        Date tenYearsLater = cal.getTime();
        // 1. 查询所有处于 "进行中" 状态的项目 (假设状态值为 "in_progress", 请根据你的实际情况修改)
        Project projectQuery = new Project();
        projectQuery.setProjectStatus("1"); // 筛选进行中的项目，如果想给所有项目添加，则 new Project() 即可
        List<Project> projectList = projectMapper.selectProjectList(projectQuery);

        if (projectList == null || projectList.isEmpty()) {
            return 0; // 如果没有项目，直接返回0
        }








        List<String> allProjectIds = projectList.stream()
                .map(Project::getProjectId)
                .collect(Collectors.toList());

        // 3. 一次性查询出在这些项目中，哪些已经有了这个任务
        // 使用 Set 提高后续判断效率
        Set<String> projectsAlreadyHaveTask = new HashSet<>();
        if (!allProjectIds.isEmpty()) {
            projectsAlreadyHaveTask.addAll(taskMapper.selectProjectIdsByTaskName(taskName, allProjectIds));
        }

        // 4. 遍历项目列表，为“需要添加任务”的项目构建Task对象
        List<Task> taskListToInsert = new ArrayList<>();
        for (Project project : projectList) {
            // 如果项目ID不在“已存在任务的Set”中，则为该项目创建任务
            if (!projectsAlreadyHaveTask.contains(project.getProjectId())) {
                Task newTask = new Task();

                // 复制模板信息
                newTask.setTaskName(taskName);
                newTask.setTaskDesc(taskTemplate.getTaskDesc());
                newTask.setPriority(taskTemplate.getPriority());
                newTask.setStartTime(now);
                newTask.setEndTime(tenYearsLater);
                newTask.setStatus("1");

                // 设置项目关联ID
                newTask.setProjectId(project.getProjectId());

                // 生成唯一的Task Code (项目ID + 短UUID)
                String taskCode = project.getProjectId() + "-" + UUID.randomUUID().toString().substring(0, 8);
                newTask.setTaskCode(taskCode);

                // 设置创建人信息
                newTask.setCreateBy(operator);
                taskListToInsert.add(newTask);
            }
        }

        // 5. 调用Mapper进行批量插入
        if (taskListToInsert.isEmpty()) {
            return 0; // 没有需要添加的任务
        }
        int taskRows = taskMapper.batchInsertTask(taskListToInsert);
        if(taskRows == 0){
            // 插入失败，可以抛出异常或返回错误信息
            throw new ServiceException("批量创建任务失败");
        }
        // ======================= 阶段二：准备并批量插入任务成员 =======================
        List<TaskMember> memberListToInsert = new ArrayList<>();

        // 遍历刚刚插入成功的任务列表
        for (Task createdTask : taskListToInsert) {
            Long newTaskId = createdTask.getId(); // 获取新任务的ID
            String projectId = createdTask.getProjectId(); // 获取任务所属的项目ID

            // 根据项目ID查询所有项目成员的user_id
            List<ProjectUser> projectUsers = projectUserMapper.selectProjectUserByProjectId(projectId);
            List<String> userIds = projectUsers.stream().map(w->{
                return w.getDdUserId();
            }).collect(Collectors.toList());
            if (userIds != null && !userIds.isEmpty()) {
                for (String userId : userIds) {
                    TaskMember newMember = new TaskMember();
                    newMember.setTaskId(newTaskId);
                    newMember.setUserId(userId);
                    newMember.setRole("");

                    memberListToInsert.add(newMember);
                }
            }
        }

        // 执行任务成员的批量插入
        if (!memberListToInsert.isEmpty()) {
            taskMemberMapper.batchInsertTaskMember(memberListToInsert);
        }

        return taskRows; // 返回成功创建的任务数量
    }

    /**
     * 查询任务列表
     * 
     * @param task 任务
     * @return 任务
     */
    @Override
    public List<Task> selectTaskList(Task task)
    {
        return taskMapper.selectTaskList(task);
    }

    /**
     * 新增任务
     * 
     * @param task 任务
     * @return 结果
     */
    @Override
    public int insertTask(Task task)
    {
        task.setCreateTime(DateUtils.getNowDate());
        return taskMapper.insertTask(task);
    }

    /**
     * 修改任务
     * 
     * @param task 任务
     * @return 结果
     */
    @Override
    public int updateTask(Task task)
    {
        task.setUpdateTime(DateUtils.getNowDate());
        return taskMapper.updateTask(task);
    }

    /**
     * 批量删除任务
     * 
     * @param ids 需要删除的任务主键
     * @return 结果
     */
    @Override
    public int deleteTaskByIds(Long[] ids)
    {
        return taskMapper.deleteTaskByIds(ids);
    }

    /**
     * 删除任务信息
     * 
     * @param id 任务主键
     * @return 结果
     */
    @Override
    public int deleteTaskById(Long id)
    {
        return taskMapper.deleteTaskById(id);
    }

    @Override
    public List<TaskVo> currentTask(Date startTime) {
        // 获取当前登录用户
        LoginUser user = SecurityUtils.getLoginUser();
        if (user == null) {
            return new ArrayList<>();
        }
        List<TaskVo> task =  taskMapper.currentTask(user.getUser().getDdUserId(), startTime);

        return task;
    }

    @Override
    public TaskInfoVo queryTaskInfo(Long taskId) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser getUser = loginUser.getUser();
        List<Long> roleIds = roleMapper.selectRoleListByUserId(getUser.getUserId());
        Long role1 = roleMapper.selectRoleIdByName("销售");
        Long role2 = roleMapper.selectRoleIdByName("主管");
        //查询任务信息
        TaskInfoVo TaskInfo = taskMapper.queryTaskInfoById(taskId);
        Project project = projectMapper.selectProjectInfoByProjectId(TaskInfo.getProjectId());
        //查询任务成员
        List<TaskMember> tm =  taskMemberMapper.selectTaskMemberByTaskId(taskId);
        //如果没有任务成员，返回空列表
        if (tm.size() <= 0) {
            TaskInfo.setTaskMembers(new ArrayList<>());
            return TaskInfo;
        }
        //查询任务成员对应的用户信息
        List<TaskMemberVo> vos = tm.stream().map(x -> {
            TaskMemberVo vo = new TaskMemberVo();
            BeanUtils.copyBeanProp(vo, x);
            SysUser sysUser = userMapper.selectUserByDdUserId(x.getUserId());
            SysUserVo userVo = new SysUserVo();
            BeanUtils.copyBeanProp(userVo, sysUser);
            vo.setUser(userVo);
            return vo;
        }).collect(Collectors.toList());
        TaskInfo.setTaskMembers(vos);
        // 我提交的工时记录
        String userId = SecurityUtils.getLoginUser().getUser().getDdUserId();
        List<Worklog> worklog = worklogMapper.selectWorkLogByUserIdAndTaskId(userId, taskId);
        TaskInfo.setWorklogs(worklog);
        if (roleIds.contains(role2)||project.getSaleId().equals(getUser.getDdUserId())|| project.getProjectLeader().equals(getUser.getDdUserId())){
            TaskInfo.setCanFinish(true);
        }else{
            TaskInfo.setCanFinish(false);
        }
//        Date today = new Date();
        LocalDate localDate = LocalDate.now();
        BigDecimal loggedHours = worklogMapper.selectMyLeftWorkHours(localDate,getUser.getDdUserId());
        BigDecimal leftHours = TOTAL_HOURS_IN_DAY.subtract(loggedHours);
        TaskInfo.setLeftHours(leftHours);
        return TaskInfo;
    }

    @Override
    public int completeTask(CompleteTaskDto dto) {
        Task task = taskMapper.selectTaskById(dto.getTaskId());
        if (task == null) {
            throw new ServiceException("任务不存在");
        }
        task.setStatus("0"); // 设置任务状态为已完成
        return taskMapper.updateTask(task);
    }

    @Override
    public List<MyTaskInfoVo> getMyTask(SysUser user) {
        return taskMapper.selectMyTasksByUserId(user.getDdUserId());
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void createTask(CreateTaskDTO dto) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        //renwu
        Task task = new Task();
        BeanUtils.copyProperties(dto,task);
        task.setStatus("1");
        task.setCreateTime(DateUtils.getNowDate());
        String taskCode = UUID.randomUUID().toString().substring(0,6);
        task.setTaskCode("TASK"+taskCode.toUpperCase());
        task.setCreateBy(user.getDdUserId());
        taskMapper.insertTask(task);


        dto.getUserIds().forEach(w->{
            TaskMember taskMember = new TaskMember();
            taskMember.setTaskId(task.getId());
            taskMember.setUserId(w);
            taskMember.setJoinTime(DateUtils.getNowDate());
            taskMemberMapper.insertTaskMember(taskMember);
        });

    }

    @Override
    public void appUpdateTask(UpdateTaskDTO dto) {
        Task task = taskMapper.selectTaskById(dto.getTaskId());
        BeanUtils.copyProperties(dto,task);
        taskMapper.updateTask(task);
        taskMemberMapper.deleteByTaskId(dto.getTaskId());
        dto.getUserIds().forEach(w->{
            TaskMember taskMember = new TaskMember();
            taskMember.setTaskId(task.getId());
            taskMember.setUserId(w);
            taskMember.setJoinTime(DateUtils.getNowDate());
            taskMemberMapper.insertTaskMember(taskMember);
        });
    }

    @Override
    public List<UserTaskVO> getUserTaskInfo(String projectId) {
        List<Task> tasks = taskMapper.selectTaskListByProjectId(projectId);
        List<UserTaskVO> userTaskVOS = tasks.stream().map(w->{
            UserTaskVO userTaskVO = new UserTaskVO();
            userTaskVO.setTask(w);
            List<TaskMember> taskMember = taskMemberMapper.selectTaskMemberByTaskId(w.getId());
            List<TaskUserVo> taskUserVos = taskMember.stream().map(x->{
                SysUser sysUser = userMapper.selectUserByDdUserId(x.getUserId());
                TaskUserVo taskUserVo1 = new TaskUserVo();
                taskUserVo1.setDdUserId(sysUser.getDdUserId());
                taskUserVo1.setUserName(sysUser.getNickName());
                return taskUserVo1;
            }).collect(Collectors.toList());

            userTaskVO.setTaskUserVo(taskUserVos);
            return userTaskVO;
        }).collect(Collectors.toList());

        return userTaskVOS;
    }

    @Override
    @Scheduled(cron = "0 */5 * * * ?")
    public void preHot() {
        List<String> nameList = taskMapper.selectName();
        System.out.println("im alive!");
    }
}
